import os
import sys
sys.path.insert(0, os.path.abspath(os.path.dirname(__file__) + '/../'))
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'keepback.settings')
import django
django.setup()

from home.models import Video
from elasticsearch import Elasticsearch

es = Elasticsearch(['http://localhost:9200'])

def sync_videos():
    videos = Video.objects.all()
    for video in videos:
        doc = {
            "id": video.id,
            "title": video.title,
            "cover": video.cover,
            "author": video.author,
            "author_avatar": video.author_avatar,
            "duration": video.duration,
            "views": video.views,
            "time": video.time
        }
        # 如果有created_at字段，格式化
        if hasattr(video, 'created_at') and video.created_at:
            doc["created_at"] = video.created_at.strftime('%Y-%m-%dT%H:%M:%S')
        es.index(index="videos", id=video.id, document=doc)
    print(f"已同步 {videos.count()} 个视频到 ES")

if __name__ == "__main__":
    sync_videos()